<template>
  <el-card class="enter-container">
    <div slot="header" class="clearfix">
      <span>试题录入</span>
    </div>
    <el-form :model="questionForm" :rules="questionFormRules" ref="questionFormRef">
      <el-form-item label="学科：" prop="subjectID" label-width="120px">
        <el-select class="select-width" v-model="questionForm.subjectID" placeholder="请选择"
          @focus="getSubjectList">
          <el-option v-for="item in subjectList" :key="item.value" :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录：" prop="catalogID" label-width="120px">
        <el-select class="select-width" v-model="questionForm.catalogID" placeholder="请选择"
          @focus="handlersecondCatalog">
          <el-option v-for="item in secondCatalog" :key="item.value" :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="企业：" prop="enterpriseID" label-width="120px">

        <el-select class="select-width" v-model="questionForm.enterpriseID" placeholder="请选择"
          @focus="getCompanyList">
          <el-option v-for="item in companyList" :key="item.id" :label="item.company"
            :value="item.id">
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item label="城市：" prop="province" label-width="120px">
        <el-row type="flex" justify="space-between" class="select-width">
          <el-col>
            <el-select size="small" v-model="questionForm.province" placeholder="请选择"
              @change="choseProvince" @focus="loadingProvinceList">

              <el-option v-for="item in province" :key="item.value" :label="item.label"
                :value="item.value">
              </el-option>

            </el-select>
          </el-col>
          <el-col class="city-margin">
            <el-form-item prop="city">
              <el-select size="small" v-model="questionForm.city" placeholder="请选择">
                <el-option v-for="item in citys" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="方向：" prop="direction" label-width="120px">
        <el-select class="select-width" size="small" v-model="questionForm.direction"
          placeholder="请选择">
          <el-option v-for="item in direction" :key="item.value" :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题型：" prop="questionType" label-width="120px">
        <el-radio-group v-model="questionForm.questionType">
          <el-radio :label="1">单选</el-radio>
          <el-radio :label="2">多选</el-radio>
          <el-radio :label="3">简答</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="难度：" prop="difficulty" label-width="120px">
        <el-radio-group v-model="questionForm.difficulty">
          <el-radio :label="1">简单</el-radio>
          <el-radio :label="2">一般</el-radio>
          <el-radio :label="3">困难</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 题干 -->
      <el-form-item label="题干：" prop="question" label-width="120px">
        <quill-editor v-model="questionForm.question" :options="editorOption"></quill-editor>
      </el-form-item>
      <!-- 选项--单选 -->
      <el-form-item v-if="questionForm.questionType === 1" label="选项：" label-width="120px">
        <el-row class="row-padding-bottom" v-for=" (item,index) in radioList" :key="item.code" :gutter="5" align="middle" type="flex">
          <el-col :span="1.2">
            <el-radio @change="changeRadio" v-model="isRight" :label="index">{{ item.code }}：</el-radio>
          </el-col>
          <el-col :span="6">
            <el-input v-model="item.title"></el-input>
          </el-col>
          <el-col :span="4" style="position:relative">
            <el-upload class="avatar-uploader" :show-file-list="false" action="">
              <span class="avatar-uploader-icon">上传图片</span>
            <i class="el-icon-close close-label"></i>
            </el-upload>
          </el-col>
        </el-row>
        <el-row>
          <el-button type="danger" size="small" :disabled="questionForm.questionType !== 2">+添加选项与答案</el-button>
        </el-row>
      </el-form-item>
      <!-- 选项--多选 -->
      <el-form-item v-else-if="questionForm.questionType === 2" label="选项：" label-width="120px">
        <el-checkbox-group v-model="checkList">
        <el-row class="row-padding-bottom" v-for="(item,index) in checkoutList" :key="item.code" :gutter="5" align="middle" type="flex">
          <el-col :span="1.2">
            <el-checkbox :label="index">{{ item.code }}：</el-checkbox>
          </el-col>
          <el-col :span="6">
            <el-input v-model="item.title"></el-input>
          </el-col>
          <el-col :span="4" style="position:relative">
            <el-upload class="avatar-uploader" :show-file-list="false" action="">
              <span class="avatar-uploader-icon">上传图片</span>
            <i class="el-icon-close close-label"></i>
            </el-upload>
          </el-col>
        </el-row>
     </el-checkbox-group>
        <el-row>
          <el-button type="danger" size="small" @click="addOptions" :disabled="questionForm.questionType !== 2">+添加选项与答案</el-button>
        </el-row>
      </el-form-item>
      <!-- 解析视频 -->
      <el-form-item label="解析视频：" prop="videoURL" label-width="120px">
        <el-input class="select-width" v-model="questionForm.videoURL"></el-input>
      </el-form-item>
      <!-- 答案解析 -->
      <el-form-item label="答案解析：" prop="answer" label-width="120px">
        <quill-editor v-model="questionForm.answer" :options="editorOption" ref="myQuillEditor"></quill-editor>
      </el-form-item>
    <!-- 题目备注 -->
      <el-form-item label="题目备注：" prop="remarks" label-width="120px">
          <el-input
          class="select-width"
            type="textarea"
            :rows="4"
            placeholder=""
            v-model="questionForm.remarks">
          </el-input>
      </el-form-item>
      <el-form-item label="试题标签：" prop="tags" label-width="120px">
        <el-select class="select-width" size="small" v-model="questionForm.tags"
          placeholder="请选择试题标签" @focus="handlersubjectLabel" multiple>
          <el-option v-for="item in tags" :key="item.value" :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label-width="120px">
        <el-button :type="$route.query.id ? 'success' : 'primary'" @click="submitOnConfirm">{{ $route.query.id ? '确认修改' : '确认提交' }}</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { simple as directorysSimpleList } from '@/api/hmmm/directorys'
import { list as companyListAPI } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction } from '@/api/hmmm/constants'
import { simple as tagsSimpleList } from '@/api/hmmm/tags'
import hljs from 'highlight.js'
import { add, detail } from '@/api/hmmm/questions'
export default {
  name: 'EnterQuestions',
  data () {
    return {
      questionForm: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: 1,
        difficulty: 1,
        question: '',
        options: [],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: []
      },
      questionFormRules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'blur' }],
        province: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }]

      },
      subjectList: [],
      secondCatalog: [],
      companyList: [],
      province: [],
      citys: [],
      direction,
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image', 'link']
          ],
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        }
      },
      optionsCheckBoxAll: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
      tags: [],
      isRight: '',
      isChkRight: 1,
      radioList: [{
        code: 'A',
        title: '',
        img: '',
        isRight: 0
      },
      {
        code: 'B',
        title: '',
        img: '',
        isRight: 0
      },
      {
        code: 'C',
        title: '',
        img: '',
        isRight: 0
      },
      {
        code: 'D',
        title: '',
        img: '',
        isRight: 0
      }],
      checkoutList: [
        {
          code: 'A',
          title: '',
          img: '',
          isRight: 0
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: 0
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: 0
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: 0
        }
      ],
      checkList: []
    }
  },
  created () {
    this.loadingDirection()
    if (this.$route.query?.id) {
      // console.log(this.$route.query.id)
      this.renderEdit(this.$route.query.id)
    }
  },
  methods: {
    // 根据 id 渲染数据
    async renderEdit (id) {
      try {
        const { data } = await detail({ id })
        // 富文本编辑器神坑处理
        this.$nextTick(function () {
          this.$refs.myQuillEditor.quill.enable(false)
          this.$refs.myQuillEditor.quill.blur()
        })
        this.questionForm = data
        this.questionForm.questionType = this.questionForm.questionType - 0
        this.questionForm.difficulty = this.questionForm.difficulty - 0
        this.questionForm.tags = this.questionForm.tags.split(',')
        // console.log(data.questionType)
        this.getSubjectList()
        this.handlersecondCatalog()
        this.getCompanyList()
        this.handlersubjectLabel()
        if (data.questionType === 1) {
          data.options.forEach((item, index) => {
            if (item.isRight === 1) {
              this.isRight = index
            }
          })
          this.radioList = data.options
        } else if (data.questionType === 2) {
          data.options.forEach((item, index) => {
            if (item.isRight === 1) {
              this.checkList.push(index)
            }
          })
          this.checkoutList = data.options
        }
      } catch (error) {
        this.$message.error('获取数据失败')
      }
    },
    // 获取学科列表
    async getSubjectList () {
      try {
        const { data } = await simple()
        this.subjectList = data
      } catch (error) {
        this.$message.error('加载学科列表失败')
      }
    },
    // 获取二级目录
    async handlersecondCatalog () {
      try {
        if (this.questionForm.subjectID || this.questionForm.subjectID === 0) {
          const { data } = await directorysSimpleList({
            subjectID: this.questionForm.subjectID
          })
          this.secondCatalog = data
        }
      } catch (error) {
        this.$message.error('失败')
      }
    },
    // 获取企业列表
    async getCompanyList () {
      try {
        const { data } = await companyListAPI()
        // console.log(data)
        this.companyList = data.items
      } catch (error) {
        this.$message.error('获取企业列表数据失败')
      }
    },
    // 加载省份列表
    loadingProvinceList () {
      this.province = provinces().map((item) => {
        return {
          value: item,
          label: item
        }
      })
    },
    // 选择城市
    choseProvince (val) {
      this.questionForm.city = ''
      this.citys = citys(val).map((item) => {
        return {
          value: item,
          label: item
        }
      })
    },
    // 处理方向
    loadingDirection () {
      this.direction = this.direction.map((item) => {
        return {
          value: item,
          label: item
        }
      })
    },
    // 处理学科标签
    async handlersubjectLabel () {
      try {
        if (this.questionForm.subjectID || this.questionForm.subjectID === 0) {
          const { data } = await tagsSimpleList({
            subjectID: this.questionForm.subjectID
          })
          // console.log(data)
          this.tags = data
        }
      } catch (error) {
        this.$message.error('加载标签列表失败')
      }
    },
    // 增加选项
    addOptions () {
      this.checkoutList.push({
        code: this.optionsCheckBoxAll[this.checkoutList.length],
        title: '',
        img: '',
        isRight: 0
      })
    },
    // 改变单选
    changeRadio (val) {
      this.radioList.forEach((item, index) => {
        if (index === val) {
          item.isRight = true
          return
        }
        item.isRight = false
      })
    },
    submitOnConfirm () {
      this.$refs.questionFormRef.validate(async isOk => {
        if (isOk) {
          try {
            this.questionForm.questionType = this.questionForm.questionType + ''
            this.questionForm.difficulty = this.questionForm.difficulty + ''
            if (Array.isArray(this.questionForm.tags)) {
              this.questionForm.tags = this.questionForm.tags.join(' ')
            }
            const newQuestionForm = JSON.parse(JSON.stringify(this.questionForm))
            if (this.questionForm.questionType === '1') {
              newQuestionForm.options = this.radioList
            } else if (this.questionForm.questionType === '2') {
              this.checkoutList.forEach((item, index) => {
                if (this.checkList.includes(index)) {
                  item.isRight = true
                  return
                }
                item.isRight = false
              })
              newQuestionForm.options = this.checkoutList
            }
            await add(newQuestionForm)
            this.$message.success('修改成功')
            this.$router.push({
              name: 'questions-list'
            })
          } catch (error) {
            this.$message.error('试题录入失败')
          }
        }
      })
    }

  }
}
</script>

<style scoped lang='less'>
.enter-container {
  margin: 20px;
  .card-box {
    border-bottom: 1px solid #000;
  }
  .select-width {
    width: 400px;
  }
  .city-margin {
    margin-left: 5px;
  }
  /deep/.ql-toolbar {
    padding: 0 8px;
  }
  /deep/.ql-editor {
    height: 200px;
  }
  /deep/.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    // overflow: hidden;
    width: 100px;
    height: 60px;
  }
  /deep/ .avatar-uploader {
    height: 60px;
  }
  /deep/ .el-upload:hover {
    border-color: #409eff;
  }
  /deep/ .avatar-uploader-icon {
    font-size: 14px;
    // color: #8c939d;
    line-height: 60px;
    text-align: center;
  }
  .close-label {
    position: absolute;
    right: 0;
    top: 0;
    -webkit-transform: translate(50%,-50%);
    transform: translate(50%,-50%);
    background: #fff;
    font-size: 14px;
    color: #999;
    border-radius: 50%;
    border: 1px #666 solid;
    z-index: 999;
  }
  .row-padding-bottom {
    padding-bottom: 20px;
  }
}
</style>
